<template>
  <div class="user-profile-page">
    <!-- 主卡片容器 -->
    <div class="profile-card-container">
      <!-- 骨架屏 -->
      <div v-if="loading" class="skeleton-container">
        <div class="skeleton-card">
          <div class="skeleton-header">
            <div class="skeleton-avatar"></div>
            <div class="skeleton-info">
              <div class="skeleton-username"></div>
              <div class="skeleton-stats">
                <div class="skeleton-stat"></div>
                <div class="skeleton-stat"></div>
                <div class="skeleton-stat"></div>
                <div class="skeleton-stat"></div>
              </div>
            </div>
          </div>
          <div class="skeleton-tags">
            <div class="skeleton-tag"></div>
            <div class="skeleton-tag"></div>
            <div class="skeleton-tag"></div>
            <div class="skeleton-tag"></div>
          </div>
          <div class="skeleton-completion"></div>
          <div class="skeleton-intro"></div>
        </div>
      </div>

      <!-- 实际内容 -->
      <div v-else class="profile-card">
        <!-- 用户信息头部 -->
        <div class="profile-header">
          <!-- 返回按钮 -->
          <div class="back-button">
            <el-button type="text" @click="goBack()" class="back-btn">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
          </div>
          <div class="user-avatar-section">
            <div class="user-avatar" @click="triggerAvatarUpload">
              <img
                :src="userDetailForm.headImage || defaultAvatar"
                :alt="userDetailForm.nickName || '用户头像'"
                class="avatar-img"
              />
              <div class="avatar-overlay">
                <el-icon class="upload-icon"><Camera /></el-icon>
                <span class="upload-text">更换头像</span>
              </div>
              <!-- 隐藏的文件上传 -->
              <input
                ref="avatarInput"
                type="file"
                accept="image/*"
                @change="handleAvatarChange"
                style="display: none"
              />
            </div>
            <div class="user-info">
              <div class="username-section">
                <h1 class="username">{{ userDetailForm.nickName || '用户' }}</h1>
                <div class="user-badge">
                  <el-tag type="warning" size="small">活跃用户</el-tag>
                </div>
              </div>
              <div class="user-stats">
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.solvedCount || 0 }}</div>
                  <div class="stat-label">已解决</div>
                </div>
                <div class="stat-divider"></div>
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.favoriteCount || 0 }}</div>
                  <div class="stat-label">收藏</div>
                </div>
                <div class="stat-divider"></div>
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.submitCount || 0 }}</div>
                  <div class="stat-label">提交</div>
                </div>
                <div class="stat-divider"></div>
                <div class="stat-item">
                  <div class="stat-number">{{ userStats.rating || 0 }}</div>
                  <div class="stat-label">积分</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 用户详细信息标签 -->
          <div class="user-tags">
            <div class="tag-item" v-if="userDetailForm.email">
              <el-icon><Message /></el-icon>
              <span>{{ userDetailForm.email }}</span>
            </div>
            <div class="tag-item" v-if="userDetailForm.schoolName">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ userDetailForm.schoolName }}</span>
            </div>
            <div class="tag-item" v-if="userDetailForm.majorName">
              <el-icon><Clock /></el-icon>
              <span>{{ userDetailForm.majorName }}</span>
            </div>
            <div class="tag-item" v-if="userDetailForm.phone">
              <el-icon><Check /></el-icon>
              <span>已认证</span>
            </div>
            <div class="tag-item">
              <el-icon><Location /></el-icon>
              <span>IP属地: 未知</span>
            </div>
          </div>

          <!-- 个人资料完善度 -->
          <div class="profile-completion">
            <span class="completion-text">个人资料完善度: {{ profileCompletion }}%</span>
            <el-button type="text" @click="openEditDrawer" class="edit-link">去编辑 ></el-button>
          </div>

          <!-- 个人介绍 -->
          <div class="user-intro-display">
            <p class="intro-text">{{ userDetailForm.introduce || '点击添加简介, 让大家认识你' }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Tab 导航 -->
    <div class="tab-navigation">
      <div class="tab-container">
        <div
          class="tab-item"
          :class="{ active: $route.path === '/home/user/detail/info' }"
          @click="switchTab('/home/user/detail/info')"
        >
          个人信息
        </div>
        <div
          class="tab-item"
          :class="{ active: $route.path === '/home/user/detail/favorite' }"
          @click="switchTab('/home/user/detail/favorite')"
        >
          我的收藏
        </div>
      </div>
    </div>

    <!-- Tab 内容区域 -->
    <div class="tab-content">
      <router-view />
    </div>
  </div>
</template>

<script setup>
import { getUserDetailService, updateHeadImageService } from '@/apis/user'
import { getToken } from '@/utils/cookie'
import { useUserStore } from '@/stores'
import {
  ArrowLeft,
  OfficeBuilding,
  Clock,
  Check,
  Location,
  Camera,
  Message
} from '@element-plus/icons-vue'

import router from '@/router'
import { reactive, ref, onMounted, computed } from 'vue'
import { ZlMessage } from '@/utils/message'

const userStore = useUserStore()

const userDetailForm = reactive({})
const defaultAvatar = '/src/assets/user/head_image.png'
const loading = ref(true)

// 记录进入个人中心之前的真正路由
const previousRoute = ref(null)

// 用户统计数据
const userStats = ref({
  solvedCount: 0,
  favoriteCount: 0,
  submitCount: 0,
  rating: 0
})

// 头像上传相关
const avatarInput = ref(null)

// 计算个人资料完善度
const profileCompletion = computed(() => {
  let completed = 0
  const fields = ['nickName', 'sex', 'schoolName', 'majorName', 'phone', 'introduce']
  fields.forEach((field) => {
    if (userDetailForm[field]) completed++
  })
  return Math.round((completed / fields.length) * 100)
})

async function getUserDetail() {
  try {
    loading.value = true
    const userRef = await getUserDetailService()
    Object.assign(userDetailForm, userRef.data)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ZlMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

function goBack() {
  // 如果有记录的上一次路由，就返回到那里
  if (previousRoute.value) {
    router.push(previousRoute.value)
  } else {
    // 否则返回到主页
    router.push('/home')
  }
}

// 切换tab，使用replace而不是push，避免记录到历史中
function switchTab(path) {
  router.replace(path)
}

// 打开编辑抽屉
function openEditDrawer() {
  // 通过事件总线或ref调用子组件的方法
  const userInfoComponent = document.querySelector('.user-info-page')
  if (userInfoComponent && userInfoComponent.__vueParentComponent) {
    userInfoComponent.__vueParentComponent.exposed?.openEditDrawer?.()
  }
}

// 触发头像上传
function triggerAvatarUpload() {
  avatarInput.value.click()
}

// 处理头像文件选择
async function handleAvatarChange(event) {
  const file = event.target.files[0]
  if (!file) return

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    ZlMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小 (限制为2MB)
  if (file.size > 2 * 1024 * 1024) {
    ZlMessage.error('图片大小不能超过2MB')
    return
  }

  try {
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)

    // 上传文件
    const response = await fetch('/dev-api/user/file/upload', {
      method: 'POST',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      body: formData
    })

    const result = await response.json()

    if (result.code !== 1000) {
      ZlMessage.error(result.msg || '上传失败')
      return
    }

    // 更新用户头像
    const userUpdateDTO = {
      headImage: result.data.wholeFileName
    }
    await updateHeadImageService(userUpdateDTO)

    // 更新本地数据
    userDetailForm.headImage = result.data.url
    getUserDetail()

    // 更新 store 中的用户信息
    const updatedUserInfo = { ...userStore.userInfo, headImage: result.data.url }
    userStore.setUserInfo(updatedUserInfo)

    ZlMessage.success('头像上传成功')
  } catch (error) {
    console.error('头像上传失败:', error)
    ZlMessage.error('头像上传失败，请重试')
  }
}

onMounted(() => {
  getUserDetail()
  
  // 记录进入个人中心之前的真正路由
  const currentRoute = router.currentRoute.value
  const fromRoute = currentRoute.query.from || currentRoute.meta.from
  
  // 如果当前路由是个人中心的子路由，且没有记录过previousRoute
  if (currentRoute.path.includes('/home/user/detail') && !previousRoute.value) {
    // 尝试从query参数或meta中获取来源路由
    if (fromRoute) {
      previousRoute.value = fromRoute
    } else {
      // 如果没有来源信息，默认设置为home
      previousRoute.value = '/home'
    }
  }
})
</script>

<style lang="scss" scoped>
.user-profile-page {
  min-height: 100vh;
  padding: 20px 0;
}

.profile-card-container {
}

.profile-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.profile-header {
  padding: 30px;
  position: relative;

  .back-button {
    position: absolute;
    top: 20px;
    right: 20px;
    z-index: 1;

    .back-btn {
      color: #666;
      font-size: 14px;

      &:hover {
        color: #409eff;
      }
    }
  }

  .user-avatar-section {
    display: flex;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 20px;

    .user-avatar {
      flex-shrink: 0;
      position: relative;
      cursor: pointer;
      border-radius: 50%;
      overflow: hidden;

      .avatar-img {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        object-fit: cover;
        border: 3px solid #f0f0f0;
        transition: all 0.3s ease;
      }

      .avatar-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: all 0.3s ease;
        border-radius: 50%;

        .upload-icon {
          color: white;
          font-size: 20px;
          margin-bottom: 4px;
        }

        .upload-text {
          color: white;
          font-size: 12px;
          font-weight: 500;
        }
      }

      &:hover {
        .avatar-overlay {
          opacity: 1;
        }

        .avatar-img {
          transform: scale(1.05);
        }
      }
    }

    .user-info {
      flex: 1;

      .username-section {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 16px;

        .username {
          font-size: 28px;
          font-weight: 600;
          color: #222;
          margin: 0;
        }

        .user-badge {
          .el-tag {
            background: linear-gradient(45deg, #ffd700, #ffed4e);
            color: #8b4513;
            border: none;
            font-weight: 500;
          }
        }
      }

      .user-stats {
        display: flex;
        align-items: center;
        gap: 20px;

        .stat-item {
          text-align: center;

          .stat-number {
            font-size: 20px;
            font-weight: 600;
            color: #222;
            line-height: 1;
          }

          .stat-label {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
          }
        }

        .stat-divider {
          width: 1px;
          height: 30px;
          background: #e0e0e0;
        }
      }
    }
  }

  .user-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    margin-bottom: 16px;

    .tag-item {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 6px 12px;
      background: #f8f9fa;
      border-radius: 20px;
      font-size: 12px;
      color: #666;

      .el-icon {
        font-size: 14px;
      }
    }
  }

  .profile-completion {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;

    .completion-text {
      font-size: 14px;
      color: #666;
    }

    .edit-link {
      color: #409eff;
      font-size: 14px;
      padding: 0;

      &:hover {
        color: #66b1ff;
      }
    }
  }

  .user-intro-display {
    .intro-text {
      font-size: 14px;
      color: #666;
      line-height: 1.5;
      margin: 0;
      padding: 12px 16px;
      background: #f8f9fa;
      border-radius: 8px;
      border: 1px solid #e0e0e0;
    }
  }
}

.tab-navigation {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  overflow: hidden;

  .tab-container {
    display: flex;
    justify-content: flex-start;

    .tab-item {
      padding: 16px 24px;
      text-align: left;
      font-size: 16px;
      font-weight: 500;
      color: #666;
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;
      min-width: 120px;
      text-decoration: none;

      &:hover {
        color: #409eff;
        background: #f8f9fa;
      }

      &.active {
        color: #409eff;
        background: #f0f9ff;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 3px;
          background: #409eff;
        }
      }
    }
  }
}

.tab-content {
  min-height: 400px;
}

/* 骨架屏样式 */
.skeleton-container {
  .skeleton-card {
    background: white;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    margin-bottom: 20px;
    padding: 30px;

    .skeleton-header {
      display: flex;
      align-items: flex-start;
      gap: 20px;
      margin-bottom: 20px;

      .skeleton-avatar {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
      }

      .skeleton-info {
        flex: 1;

        .skeleton-username {
          width: 200px;
          height: 28px;
          background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
          background-size: 200% 100%;
          animation: skeleton-loading 1.5s infinite;
          border-radius: 4px;
          margin-bottom: 16px;
        }

        .skeleton-stats {
          display: flex;
          align-items: center;
          gap: 20px;

          .skeleton-stat {
            width: 60px;
            height: 20px;
            background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
            background-size: 200% 100%;
            animation: skeleton-loading 1.5s infinite;
            border-radius: 4px;
          }
        }
      }
    }

    .skeleton-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      margin-bottom: 16px;

      .skeleton-tag {
        width: 120px;
        height: 24px;
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: skeleton-loading 1.5s infinite;
        border-radius: 12px;
      }
    }

    .skeleton-completion {
      width: 200px;
      height: 16px;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 4px;
      margin-bottom: 16px;
    }

    .skeleton-intro {
      width: 100%;
      height: 60px;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: 8px;
    }
  }
}

/* 骨架屏动画 */
@keyframes skeleton-loading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .profile-card-container {
    padding: 0 16px;
    margin-top: 80px;
  }

  .profile-header {
    padding: 20px;

    .user-avatar-section {
      flex-direction: column;
      align-items: center;
      text-align: center;

      .user-info {
        .user-stats {
          justify-content: center;
        }
      }
    }

    .user-tags {
      justify-content: center;
    }
  }
}
</style>
